package com.yuke.cloud.service.smc.service.impl;

import com.yuke.cloud.common.core.support.BaseService;
import com.yuke.cloud.common.util.DateUtil;
import com.yuke.cloud.common.util.PublicUtil;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.omc.service.OmcOrderFeignApi;
import com.yuke.cloud.service.api.pmc.service.PmcFeignApi;
import com.yuke.cloud.service.api.uac.dto.AccEmployeeInfoDto;
import com.yuke.cloud.service.api.uac.dto.UserInfoDto;
import com.yuke.cloud.service.api.uac.service.UacUserFeignApi;
import com.yuke.cloud.service.smc.dao.DmsStoreMapper;
import com.yuke.cloud.service.smc.dto.DmsStoreDto;
import com.yuke.cloud.service.smc.entity.DmsScope;
import com.yuke.cloud.service.smc.entity.DmsStore;
import com.yuke.cloud.service.smc.service.DmsScopeService;
import com.yuke.cloud.service.smc.service.DmsStoreService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * Created by zn on 2020/07/04.
 */
@Service
@Transactional
public class DmsStoreServiceImpl extends BaseService<DmsStore> implements DmsStoreService {
    @Resource
    private DmsScopeService dmsScopeService;
    @Resource
    private DmsStoreMapper dmsStoreMapper;
    @Resource
    private UacUserFeignApi uacUserFeignApi;
    @Resource
    private PmcFeignApi pmcFeignApi;
    @Resource
    private OmcOrderFeignApi omcOrderFeignApi;

    @Override
    public List<DmsStoreDto> getStoreInfo(List<DmsStoreDto> list){

        if (list != null && list.size() > 0 ){
            //获取userId
            AccEmployeeInfoDto accEmployeeInfoDto = new AccEmployeeInfoDto();
            Wrapper<List<UserInfoDto> > userInfoDtos = uacUserFeignApi.selectEmployInfo(accEmployeeInfoDto);
            List<Long> countyIds = list.stream().map(DmsStoreDto::getCountyId).collect(Collectors.toList());
            System.out.println("这个county是否为空="+countyIds);
            List<Map> mapList = new ArrayList<>();
            if (countyIds != null && countyIds.size() > 0){
                mapList = pmcFeignApi.getRegionNameByCountyIds(countyIds);
            }

            List<DmsScope> dmsScopeList = dmsScopeService.findAll();
            if (userInfoDtos.getCode() == 200){
                List<UserInfoDto> userInfoDtoList = userInfoDtos.getResult();

                for(DmsStoreDto item : list){
                    for(UserInfoDto userInfoDto : userInfoDtoList){
                        //跟进业务员
                        if (item.getDevUserId() != null && item.getDevUserId().equals(userInfoDto.getUserId())){
                            item.setDevUserName(userInfoDto.getUserName());
                        }
                        //服务业务员
                        if (item.getServiceUserId() != null && item.getServiceUserId().equals(userInfoDto.getUserId())){
                            item.setServiceUserName(userInfoDto.getUserName());
                            break;
                        }
                    }

                    if (mapList != null && mapList.size() > 0){
                        for (Map map : mapList){
                            if (item.getCountyId() != null && map.get("ID").toString().equals(item.getCountyId().toString())){
                                item.setCityName(map.get("city").toString());
                                item.setCountyName(map.get("county").toString());
                                item.setProvinceName(map.get("province").toString());
                                break;
                            }
                        }
                    }


                    for (DmsScope dmsScope : dmsScopeList) {
                        if (dmsScope.getScopeId().equals(item.getScopeId())){
                            item.setScopeName(dmsScope.getScopeName());
                            break;
                        }
                    }

                }
            }
        }
        return list;
    }

    @Override
    public List<DmsStoreDto> selectStoreByCondition(DmsStoreDto dmsStoreDto){
        return dmsStoreMapper.selectStoreByCondition(dmsStoreDto);
    }

    @Override
    public List<DmsStoreDto> findStorePosition(DmsStoreDto dmsStoreDto,Integer distance){

        return dmsStoreMapper.findStorePosition(dmsStoreDto,distance);
    }

    @Override
    public DmsStoreDto getStoreInfoById(Long storeId){
        DmsStoreDto dmsStoreDto = new DmsStoreDto();
        dmsStoreDto.setStoreId(storeId);
        List<DmsStoreDto> dmsStoreDtos = this.selectStoreByCondition(dmsStoreDto);
        List<DmsStoreDto> dmsStoreDtoList = this.getStoreInfo(dmsStoreDtos);

        if (dmsStoreDtoList != null && dmsStoreDtoList.size() > 0){
            dmsStoreDto = dmsStoreDtoList.get(0);
        }
        return dmsStoreDto;
    }

    //业务员本月签约店铺数 store_status=1
    @Override
    public List<DmsStoreDto> partnersStore(Long userId) {

        Date beginTime = DateUtil.monthTimeBegin();

        Date endTime = DateUtil.monthTimeEnd();

        List<DmsStoreDto> list = dmsStoreMapper.partnersStoreByMonth(userId,beginTime,endTime);

        return list;
    }

    //总签约店铺数
    @Override
    public List<DmsStore> allPartnersStore(Long userId) {

        Example example = new Example(DmsStore.class);

        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("storeStatus",1);

        criteria.andEqualTo("devUserId",userId);

        List<DmsStore> list = dmsStoreMapper.selectByExample(example);

        return list;
    }

    @Override
    public List<DmsStoreDto> findPartnersStore(Long userId, String input) {
        List<DmsStoreDto> list = dmsStoreMapper.findPartnersStore(userId, input);
        return list;
    }

    @Override
    public List<DmsStoreDto> findAllStore(String input) {
        List<DmsStoreDto> list = dmsStoreMapper.findAllStore(input);
        return list;
    }



    @Override
    public List<DmsStoreDto> selectStoreByShopIds(List<Long> shopIds){
        List<DmsStoreDto> dmsStoreDtoList = dmsStoreMapper.selectStoreByShopIds(shopIds);
        List<Long> countyIds = dmsStoreDtoList.stream().map(DmsStoreDto::getCountyId).collect(Collectors.toList());
        System.out.println("由区县ID获得整个行政区划名称：selectStoreByShopIds-》161"+countyIds);
        List<Map> mapList = pmcFeignApi.getRegionNameByCountyIds(countyIds);
        if (PublicUtil.isEmpty(mapList)){
            return dmsStoreDtoList;
        }
        for(DmsStoreDto dmsStoreDto : dmsStoreDtoList){
            if (dmsStoreDto.getScopeId().equals(0)){
                dmsStoreDto.setScopeName("未填写");
            }
            for (Map map : mapList){
                if (dmsStoreDto.getCountyId() != null && map.get("ID").toString().equals(dmsStoreDto.getCountyId().toString())){
                    dmsStoreDto.setProvinceName(map.get("province").toString());
                    dmsStoreDto.setCityName(map.get("city").toString());
                    dmsStoreDto.setCountyName(map.get("county").toString());
                    break;
                }
            }
        }
        return dmsStoreDtoList;
    }

    /**
     *
     * @return
     */
    @Override
    public List<Map> countStoreOrder(){

        List<Map> mapList = new ArrayList();
       //获取所有业务员userIdList
        AccEmployeeInfoDto accEmployeeInfoDto = new AccEmployeeInfoDto();
        accEmployeeInfoDto.setEmployeeType((byte)1);//业务员
        Wrapper<List<UserInfoDto> > userInfoDtos = uacUserFeignApi.selectEmployInfo(accEmployeeInfoDto);
        if (userInfoDtos.getCode() != 200) {
            return mapList;
        }
        List<UserInfoDto> userInfoDtoList = userInfoDtos.getResult();

        //获取每个业务员服务店铺storeIdList
        DmsStoreDto dmsStoreDto = new DmsStoreDto();
        for (UserInfoDto userInfo : userInfoDtoList){
            Map map = new HashMap();
            map.put("userId",userInfo.getUserId());
            map.put("userName",userInfo.getUserName());

            dmsStoreDto.setServiceUserId(userInfo.getUserId());
            List<DmsStoreDto> dmsStoreDtoList = dmsStoreMapper.selectStoreByCondition(dmsStoreDto);
            System.out.println("查找业务员负责的店铺："+dmsStoreDtoList);
            //每个店铺下单统计
            List<Long> shopIds = dmsStoreDtoList.stream().map(DmsStoreDto::getShopId).collect(Collectors.toList());

            //当月
            Date beginTime = DateUtil.monthTimeBegin();
            Date endTime = DateUtil.monthTimeEnd();
            System.out.println(shopIds);
            Map countMap = omcOrderFeignApi.countOrderByShopIds(shopIds,beginTime,endTime);
            if (countMap != null){
                map.putAll(countMap);
            }

            mapList.add(map);
        }

        Collections.sort(mapList, new Comparator<Map>() {

            public int compare(Map o1, Map o2) {

                Long name1 = Long.valueOf(o1.get("amountPayable").toString()) ;

                Long name2 = Long.valueOf(o2.get("amountPayable").toString()) ;

                return name2.compareTo(name1);

            }

        });
        return mapList;
    }


    @Override
    public List<DmsStoreDto> findShopIdStore() {

        List<DmsStoreDto>  list = dmsStoreMapper.findShopIdStore();
        return list;
    }

    @Override
    public List<DmsStoreDto> findShopIdStore(int page,int size) {

        page=(page-1)*size;

        List<DmsStoreDto>  list = dmsStoreMapper.findShopIdStores(page,size);
        return list;
    }


    @Override
    public void batchUpdateList(Integer value,List<Long> shopIds) {
        if (shopIds!=null && shopIds.size()>0){
            dmsStoreMapper.batchUpdateLists5(value,shopIds);
        }

    }

    @Override
    public List<DmsStoreDto> joinStoreByMonth(Long userId) {
        //当月
        Date beginTime = DateUtil.monthTimeBegin();
        Date endTime = DateUtil.monthTimeEnd();
        List<DmsStoreDto> list = dmsStoreMapper.joinStoreByMonth(userId,beginTime,endTime);
        return list;
    }

    @Override
    public Integer ifServiceStore(Long userId, Long storeId) {
        DmsStore dmsStore = dmsStoreMapper.selectByPrimaryKey(storeId);
        if (dmsStore.getServiceUserId()!=null && !dmsStore.getServiceUserId().equals(0)) {
            boolean equals = dmsStore.getServiceUserId().equals(userId);
            if (equals == true) {
                //相等是服务人
                return 1;
            }
            return 0;
        }
    return 0;
    }

    @Override
    public Integer quitServiceStore(Long storeId) {

        DmsStore dmsStore = dmsStoreMapper.selectByPrimaryKey(storeId);
        if (dmsStore.getServiceUserId()!=null&&dmsStore.getServiceUserId()!=0){
            dmsStore.setServiceUserId(null);
        }
        int i = dmsStoreMapper.updateByPrimaryKey(dmsStore);
        return i;
    }

    @Override
    public Integer quitDevStore(Long storeId) {

       DmsStore dmsStore = dmsStoreMapper.selectByPrimaryKey(storeId);

        if (dmsStore.getDevUserId()!=null&&dmsStore.getDevUserId()!=0){
            dmsStore.setDevUserId(null);
        }

        int i = dmsStoreMapper.updateByPrimaryKey(dmsStore);

        return i;
    }

    @Override
    public List<DmsStore> findServiceStoreByTime(Date endDate) {

        List<DmsStore> list = dmsStoreMapper.findServiceStoreByTime(endDate);

        return list;
    }

    @Override
    public List<DmsStore> findPublicServiceStore(String input) {
        Example example = new Example(DmsStore.class);

        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("deleteTag",0).andIsNotNull("shopId").andNotEqualTo("shopId",0)
                .andCondition("(service_user_id is NULL OR service_user_id =0)");

        Example.Criteria e = example.createCriteria();

        e.andLike("storeName","%"+input+"%").orLike("address","%"+input+"%");

        example.and(e);

        List<DmsStore> list = dmsStoreMapper.selectByExample(example);

        return list;
    }

    @Override
    public List<DmsStore> findNeedServiceShop(String input) {

        Example example = new Example(DmsStore.class);

        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("deleteTag",0);

        criteria.andCondition("(shop_id is NULL OR shop_id =0)").andCondition("(service_user_id is NULL OR service_user_id =0) ")
                .andCondition("(dev_user_id is NULL OR dev_user_id =0)" );

        Example.Criteria e = example.createCriteria();

        e.andLike("storeName","%"+input+"%").orLike("address","%"+input+"%");

        example.and(e);

        List<DmsStore> list = dmsStoreMapper.selectByExample(example);

        return list;
    }

}
